package auth

import (
	"encoding/json"
	"fmt"
	"strings"

	"gitee.com/chenhonghua/ginorigin/config/http/jwt"
	"gitee.com/chenhonghua/ginorigin/config/http/restful"
	"gitee.com/chenhonghua/ginorigin/config/http/router"
	"gitee.com/chenhonghua/ginorigin/config/system/zap"

	"github.com/gin-gonic/gin"
)

type demo2Api struct{}

func Load() {
	api := demo2Api{}
	noAuthIRoutes := router.GetIRoutes("examples")

	noAuthIRoutes.POST("d2login", api.demo2Login) // 模拟登录接口，不需要拦截

	// 添加需要jwt认证的路由
	jwtAuthIRoutes := jwt.GetIRoutes("jwt")
	jwtAuthIRoutes.GET("d2h1", api.demo2ApiHandler1)
	jwtAuthIRoutes.GET("d2h2", api.demo2ApiHandler2)
}

// demo2ApiHandler1
// @Tags demo2ApiHandler1
// @Summary 样例接口1
// @Produce  application/json
// @Success 200 {object} restful.Response{data=jwt.CustomerInfo,msg=string}
// @Router /jwt/d1h1 [get]
func (demo2Api) demo2ApiHandler1(c *gin.Context) {
	// ci := jwt.GetCustomerInfo(c)
	// r := demo2ApiHandler1Resp{CustomerInfo: ci}
	restful.Success.WithDetailed(c, "样例接口1:", jwt.GetCustomerInfo(c))
}

// demo2ApiHandler2
// @Tags demo2ApiHandler2
// @Summary 样例接口2
// @Produce  application/json
// @Success 200 {object} restful.Response{data=map[string]interface{},msg=string}
// @Router /jwt/d1h2 [get]
func (demo2Api) demo2ApiHandler2(c *gin.Context) {
	restful.Success.WithMessage(c, "样例接口2")
}

type LoginResult struct {
	Username string
	Token    string
}

// Demo2Login
// @Tags Demo2Login
// @Summary 模拟登录及授权接口
// @Produce  application/json
// @Success 200 {object} restful.Response{data=LoginResult,msg=string} "模拟登录及授权接口"
// @Router /examples/d1login [Post]
func (demo2Api) demo2Login(c *gin.Context) {
	type reqJsonBody struct { // 请求格式，打样儿
		Username string
		Password string
	}
	params := reqJsonBody{}
	err := c.ShouldBindJSON(&params)
	if err != nil {
		restful.Failed.WithError(c, err)
		return
	}
	j, _ := json.MarshalIndent(params, "", "  ")
	zap.LOGGER.Debug(fmt.Sprintf("接口[%s]请求参数为：%s", "/examples/d1login", string(j)))
	// ......
	// 一系列假装登录操作
	// ......
	if strings.EqualFold("test1", params.Username) {
		// 登录成功
		// 签发jwt-token
		token, err := jwt.CreateToken(jwt.CustomerInfo{Uid: 1})
		if err == nil {
			restful.Success.WithData(c, LoginResult{
				Username: params.Username,
				Token:    token,
			})
			return
		}
	}
	// 登录失败
	restful.Failed.WithError(c, err)
}
